package com.zhou.yuefan.activity;

import java.util.ArrayList;

import com.zhou.util.Configure;
import com.zhou.util.DateAdapter;
import com.zhou.util.DragGrid;
import com.zhou.util.ScrollLayout;
import com.zhou.util.ZhouHttpPostManager;
import com.zhou.yuefan.R;
import com.zhou.yuefan.application.MyApplication;
import com.zhou.yuefan.db.DBManager;
import com.zhou.yuefan.model.Shop;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.hardware.SensorEventListener;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MiLaucherActivity extends Activity {

	/** GridView. */
	private LinearLayout linear;
	private RelativeLayout relate;
	private DragGrid gridView;
	private ScrollLayout lst_views;
	private ImageButton imgBtn_note, imgBtn_about;

	TextView tv_page;// int oldPage=1;
	private ImageView runImage, delImage;
	LinearLayout.LayoutParams param;

	TranslateAnimation left, right;
	Animation up, down;

	
	
	public static final int PAGE_SIZE = 8;
	ArrayList<DragGrid> gridviews = new ArrayList<DragGrid>();

	ArrayList<ArrayList<Shop>> lst_lstShop = new ArrayList<ArrayList<Shop>>();// 全部数据的集合集lists.size()==countpage;
	ArrayList<Shop> lst_allshop = new ArrayList<Shop>();// 每一页的数据

	// SensorManager sm;
	SensorEventListener lsn;
	boolean isClean = false;
	Vibrator vibrator;
	int rockCount = 0;
	DBManager dbManager;
	private SharedPreferences sp;
	Editor spEditor;

	ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.shops_main);
		//解决图片渐变失真问题
		getWindow().setFormat(PixelFormat.RGBA_8888);
		MyApplication myApplication = (MyApplication) getApplication();
		//单例模式
		dbManager = myApplication.getDBInstance();
		lst_allshop = (ArrayList<Shop>) dbManager.getShopList();
		imgBtn_note = (ImageButton) findViewById(R.id.img_btn_note);
		imgBtn_about = (ImageButton) findViewById(R.id.img_btn_about);
		
		
		
		imgBtn_note.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MiLaucherActivity.this,NoteActivity.class);
				startActivity(intent);
			}
		});
		
		
		//获得手机imei地址
		TelephonyManager phoneManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		final String imei = phoneManager.getDeviceId();
		final String phone = phoneManager.getLine1Number();
		
		
		
		final Animation alphaAnimation = AnimationUtils.loadAnimation(this,
				R.anim.welcome_alpha);
		alphaAnimation.setFillAfter(false);
		imageView = (ImageView) findViewById(R.id.img_welcome);
		alphaAnimation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				imageView.setVisibility(View.GONE);
				imageView.invalidate();
			}
		});
		imageView.startAnimation(alphaAnimation);

		// imageView.startAnimation(alphaAnimation);

		init();
		initData();

		for (int i = 0; i < Configure.countPages; i++) {
			lst_views.addView(addGridView(i));
		}

		lst_views.setPageListener(new ScrollLayout.PageListener() {
			@Override
			public void page(int page) {
				setCurPage(page);
			}
		});

		// 背景图片run的语句
		/*
		 * runImage = (ImageView) findViewById(R.id.run_image); runAnimation();
		 */
		delImage = (ImageView) findViewById(R.id.dels);
		relate.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("LongClick");
				return false;
			}
		});
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

		/*
		 * sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor
		 * sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); lsn = new
		 * SensorEventListener() { public void onSensorChanged(SensorEvent e) {
		 * if (e.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { if (!isClean
		 * && rockCount >= 10) { isClean = true; rockCount = 0;
		 * vibrator.vibrate(100); CleanItems(); return; } float newX =
		 * e.values[SensorManager.DATA_X]; float newY =
		 * e.values[SensorManager.DATA_Y]; float newZ =
		 * e.values[SensorManager.DATA_Z]; // if ((newX >= 18 || newY >=
		 * 20||newZ >= 20 )&&rockCount<4) // { if ((newX >= 18 || newY >= 20 ||
		 * newZ >= 20) && rockCount % 2 == 0) { rockCount++; return; } if ((newX
		 * <= -18 || newY <= -20 || newZ <= -20) && rockCount % 2 == 1) {
		 * rockCount++; return; }
		 * 
		 * } }
		 * 
		 * @Override public void onAccuracyChanged(Sensor sensor, int accuracy)
		 * { // TODO Auto-generated method stub
		 * 
		 * } };
		 * 
		 * sm.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
		 */

		sp = this.getSharedPreferences("firstLoad", MODE_PRIVATE);
		spEditor = sp.edit();
		dbManager = myApplication.getDBInstance();
		

		if (!myApplication.isDataBaseExist()) {

			dbManager.createDatabase();

		}

		final int i = sp.getInt("LT", 1);// LoadTimes，加载次数
		
		//如果网络连通，则上传加载次数
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		boolean isWifiConnected = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
		
		boolean is3GConnected = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
		
		
		//如果wifi或者3G连接了，则启动添加AddUser , LoadTime的线程
		if (isWifiConnected||is3GConnected) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//第一次启动，isUserAdded为false，则执行循环，将用户添加
					boolean addUserResult = sp.getBoolean("isUserAdded", false);
					Log.i("isUserAdded", addUserResult+"");
					while (!addUserResult) {
						addUserResult = ZhouHttpPostManager.addUser(imei, phone);
						Log.i("zhixing", "循环已经执行");
						try {
							Thread.sleep(4000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//添加用户完毕，将“用户已添加”设置为true
					spEditor.putBoolean("isUserAdded", addUserResult);
					Log.i("addUserEd", addUserResult+"");
					spEditor.commit();
					
					
					//添加访问次数成功为false，循环执行，直到访问次数添加成功
					boolean upDateLoadTimeResult = false;
					while (!upDateLoadTimeResult) {
						upDateLoadTimeResult = ZhouHttpPostManager.updateLoadTime(imei, i);
						
						Log.i("LT", upDateLoadTimeResult+"");
						try {
							Thread.sleep(4000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//访问次数上传成功后，将访问次数设置为1
					spEditor.putInt("LT", 1);
					spEditor.commit();
				}
			}).start();
		}
		//如果没有连接网络，则访问次数积累
		spEditor.putInt("LT", i+1);
		Log.i("spzhou", i + "");
		spEditor.commit();
		
	

	}

	public void init() {
		relate = (RelativeLayout) findViewById(R.id.relate);
		lst_views = (ScrollLayout) findViewById(R.id.views);
		tv_page = (TextView) findViewById(R.id.tv_page);
		tv_page.setText("1");
		Configure.init(MiLaucherActivity.this);
		param = new LinearLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		param.rightMargin = 130;
		param.leftMargin = 20;
		if (gridView != null) {
			lst_views.removeAllViews();
		}
	}

	/*
	 * 准备好一个数据结构为：ArrayList<ArrayList<String>>的数据集合，第一层表示第几屏幕；第二层表示第几个item
	 */
	public void initData() {
		// Math.ceil是指进一法取得小数的近似整数/Math.floor()用全部舍去法获得小数的近似整数
		Configure.countPages = (int) Math.ceil(lst_allshop.size()
				/ (float) PAGE_SIZE);

		// lists = new ArrayList<ArrayList<String>>();
		for (int i = 0; i < Configure.countPages; i++) {
			lst_lstShop.add(new ArrayList<Shop>());
			for (int j = PAGE_SIZE * i; j < (PAGE_SIZE * (i + 1) > lst_allshop
					.size() ? lst_allshop.size() : PAGE_SIZE * (i + 1)); j++)
				lst_lstShop.get(i).add(lst_allshop.get(j));
		}
		boolean isLast = true;

		for (int i = lst_lstShop.get(Configure.countPages - 1).size(); i < PAGE_SIZE; i++) {
			if (isLast) {
				lst_lstShop.get(Configure.countPages - 1).add(null);
				isLast = false;
			}

			/*
			 * else lst_lstShop.get(Configure.countPages - 1).add(new
			 * Shop(-1,"none"));
			 */
		}

	}
	
	

	/*
	 * 用于横竖屏切换的时候
	 */
	public void CleanItems() {
		lst_allshop = new ArrayList<Shop>();
		for (int i = 0; i < lst_lstShop.size(); i++) {
			for (int j = 0; j < lst_lstShop.get(i).size(); j++) {
				if (lst_lstShop.get(i).get(j) != null
						&& !lst_lstShop.get(i).get(j).equals("none")) {
					lst_allshop.add(lst_lstShop.get(i).get(j));
					System.out.println("-->"
							+ lst_lstShop.get(i).get(j).toString());
				}
			}
		}
		System.out.println(lst_allshop.size());
		initData();
		lst_views.removeAllViews();
		gridviews = new ArrayList<DragGrid>();
		for (int i = 0; i < Configure.countPages; i++) {
			lst_views.addView(addGridView(i));
		}
		isClean = false;
		lst_views.snapToScreen(0);
	}

	public int getFristNonePosition(ArrayList<String> array) {
		for (int i = 0; i < array.size(); i++) {
			if (array.get(i) != null && array.get(i).toString().equals("none")) {
				return i;
			}
		}
		return -1;
	}

	public int getFristNullPosition(ArrayList<String> array) {
		for (int i = 0; i < array.size(); i++) {
			if (array.get(i) == null) {
				return i;
			}
		}
		return -1;
	}

	public LinearLayout addGridView(int i) {
		// if (lists.get(i).size() < PAGE_SIZE)
		// lists.get(i).add(null);

		linear = new LinearLayout(MiLaucherActivity.this);
		gridView = new DragGrid(MiLaucherActivity.this);
		// gridView.setScrollContainer(false);
		gridView.setAdapter(new DateAdapter(MiLaucherActivity.this, lst_lstShop
				.get(i)));
		gridView.setNumColumns(2);
		gridView.setHorizontalSpacing(0);
		gridView.setVerticalSpacing(0);
		final int ii = i;
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {

				Intent intent = new Intent(MiLaucherActivity.this,
						FoodsActivity.class);
				intent.putExtra("shop_id", (int) arg3);
				startActivity(intent);
			}

		});

		gridView.setSelector(R.anim.grid_light);
		gridView.setPageListener(new DragGrid.G_PageListener() {
			@Override
			public void page(int cases, int page) {
				switch (cases) {
				case 0:// 滑动页面
					lst_views.snapToScreen(page);
					setCurPage(page);
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							Configure.isChangingPage = false;
						}
					}, 800);
					break;
				case 1:// 删除按钮上来
					delImage.setBackgroundResource(R.drawable.del);
					delImage.setVisibility(0);
					delImage.startAnimation(up);
					break;
				case 2:// 删除按钮变深
					delImage.setBackgroundResource(R.drawable.del_check);
					Configure.isDelDark = true;
					break;
				case 3:// 删除按钮变淡
					delImage.setBackgroundResource(R.drawable.del);
					Configure.isDelDark = false;
					break;
				case 4:// 删除按钮下去
					delImage.startAnimation(down);
					break;
				case 5:// 松手动作
					delImage.startAnimation(down);
					// Configure.isDelRunning = false;
					lst_lstShop.get(Configure.curentPage).add(
							Configure.removeItem, null);
					lst_lstShop.get(Configure.curentPage).remove(
							Configure.removeItem + 1);
					((DateAdapter) ((gridviews.get(Configure.curentPage))
							.getAdapter())).notifyDataSetChanged();
					break;
				}
			}
		});
		gridView.setOnItemChangeListener(new DragGrid.G_ItemChangeListener() {
			@Override
			public void change(int from, int to, int count) {
				Shop fromShop = (Shop) lst_lstShop.get(
						Configure.curentPage - count).get(from);

				lst_lstShop.get(Configure.curentPage - count).add(from,
						(Shop) lst_lstShop.get(Configure.curentPage).get(to));
				lst_lstShop.get(Configure.curentPage - count).remove(from + 1);
				lst_lstShop.get(Configure.curentPage).add(to, fromShop);
				lst_lstShop.get(Configure.curentPage).remove(to + 1);

				((DateAdapter) ((gridviews.get(Configure.curentPage - count))
						.getAdapter())).notifyDataSetChanged();
				((DateAdapter) ((gridviews.get(Configure.curentPage))
						.getAdapter())).notifyDataSetChanged();

			}
		});
		gridviews.add(gridView);
		linear.addView(gridviews.get(i), param);
		return linear;
	}

	public void runAnimation() {

		down = AnimationUtils.loadAnimation(MiLaucherActivity.this,
				R.anim.del_down);
		up = AnimationUtils
				.loadAnimation(MiLaucherActivity.this, R.anim.del_up);
		down.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				delImage.setVisibility(8);
			}
		});

		right = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
				Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT,
				0, Animation.RELATIVE_TO_PARENT, 0);
		left = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1,
				Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
				0, Animation.RELATIVE_TO_PARENT, 0);
		right.setDuration(25000);
		left.setDuration(25000);
		right.setFillAfter(true);
		left.setFillAfter(true);

		right.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				runImage.startAnimation(left);
			}
		});
		left.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				runImage.startAnimation(right);
			}
		});
		runImage.startAnimation(right);
	}

	public void setCurPage(final int page) {
		Animation a = AnimationUtils.loadAnimation(MiLaucherActivity.this,
				R.anim.scale_in);
		a.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				tv_page.setText((page + 1) + "");
				tv_page.startAnimation(AnimationUtils.loadAnimation(
						MiLaucherActivity.this, R.anim.scale_out));
			}
		});
		tv_page.startAnimation(a);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		// sm.unregisterListener(lsn);

	}

}
